<template>
  <a-drawer :open="visible" title="回库签收" @close="onClose" width="1200px">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <!-- <template #extra>
      <a-space :size="5">
        <span>
          <CopyText :text="options.return_no" />
        </span>
        <span>{{ options.driver?.name }}</span>
        <span>{{ options.create_time }}</span>
        <a-button type="link" @click="changeLogModal(true)">查看日志</a-button>
        <a-button @click="print">
          <template #icon>
            <PrinterOutlined />
          </template>
          打印({{ options?.printLog?.print_count ?? 0 }})
        </a-button>
      </a-space>
    </template> -->

    <a-card size="small" title="基本信息">
      <a-descriptions size="small" :column="3">
        <a-descriptions-item label="回库单号">
          <CopyText :text="options.return_no" />
        </a-descriptions-item>
        <a-descriptions-item label="司机">{{ options.driver?.name }}</a-descriptions-item>
        <a-descriptions-item label="回库仓库">
          <span>
            {{ options.intoWarehouse?.name }}
            <span v-if="options.intoWarehouse?.attribute_type"> ({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', options.intoWarehouse?.attribute_type) }}) </span>
          </span>
        </a-descriptions-item>
        <a-descriptions-item label="出库仓库">
          <span>
            {{ options.driverWarehouse?.name }}
            <span v-if="options.driverWarehouse?.attribute_type"> ({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', options.driverWarehouse?.attribute_type) }}) </span>
          </span>
        </a-descriptions-item>
        <a-descriptions-item label="回库类型">
          <span>{{ getDescByValue('RETURNWAREHOUSE_TYPE_ENUM', Number(options.return_type)) }}</span>
        </a-descriptions-item>
        <a-descriptions-item label="回库状态">
          <span>{{ getDescByValue('RETURNWAREHOUSE_STATUS_ENUM', Number(options.return_status)) }}</span>
        </a-descriptions-item>
        <a-descriptions-item label="订单数量">{{ options.order_count }}</a-descriptions-item>
        <a-descriptions-item label="订单金额">{{ options.order_amount }}</a-descriptions-item>
        <a-descriptions-item label="签收数量">
          <span>{{ options?.sign_large_qty }}整{{ options?.sign_middle_qty }}中{{ options?.sign_small_qty }}散</span>
        </a-descriptions-item>
        <a-descriptions-item label="签收金额">{{ options.sign_amount }}</a-descriptions-item>
        <a-descriptions-item label="单据时间">{{ options.create_time }}</a-descriptions-item>
        <a-descriptions-item label="签收时间">{{ options.sign_time }}</a-descriptions-item>
        <a-descriptions-item label="签收备注" :span="3">
          <a-input v-model:value="sign_remark" placeholder="请输入签收备注" style="width: 200px"></a-input>
        </a-descriptions-item>
      </a-descriptions>
    </a-card>

    <a-card class="smart-margin-top10" size="small" title="商品明细">
      <a-table :dataSource="tableData" :columns="columns" :pagination="false" rowKey="goods_id" size="small" bordered :scroll="{ x: 1000 }">
        <template #bodyCell="{ text, record, column }">
          <!-- 大规格数量 -->
          <template v-if="column.dataIndex === 'large_editable_qty'">
            <a-input-number v-if="record.large_spec_id" v-model:value="record.large_editable_qty" :disabled="options.return_status !== 1" :min="0" :max="record.large_initial_qty" style="width: 100%" placeholder="0" />
            <span v-else>-</span>
          </template>

          <!-- 中规格数量 -->
          <template v-if="column.dataIndex === 'medium_editable_qty'">
            <a-input-number v-if="record.medium_spec_id" v-model:value="record.medium_editable_qty" :disabled="options.return_status !== 1" :min="0" :max="record.medium_initial_qty" style="width: 100%" placeholder="0" />
            <span v-else>-</span>
          </template>

          <!-- 小规格数量 -->
          <template v-if="column.dataIndex === 'small_editable_qty'">
            <a-input-number v-if="record.small_spec_id" v-model:value="record.small_editable_qty" :disabled="options.return_status !== 1" :min="0" :max="record.small_initial_qty" style="width: 100%" placeholder="0" />
            <span v-else>-</span>
          </template>

          <!-- 单位显示 -->
          <template v-if="['large_unit_name', 'medium_unit_name', 'small_unit_name'].includes(column.dataIndex)">
            {{ text || '-' }}
          </template>

          <!-- 生产日期 -->
          <template v-if="column.dataIndex === 'batch_time'">
            <a-date-picker v-model:value="record.batch_time" value-format="YYYY-MM-DD" style="width: 100%" :disabled="options.return_status !== 1" placeholder="选择日期" />
          </template>
        </template>
      </a-table>
    </a-card>

    <LogModal v-model:open="showLogModal" @close="changeLogModal(false)" :tableData="optionsList?.printLog" />

    <template #footer>
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
      <a-button style="margin-right: 8px" type="primary" @click="submit" :loading="caigouLoading" :disabled="caigouLoading || options.return_status !== 1"> 签收 </a-button>
    </template>
  </a-drawer>
</template>

<script setup lang="ts">
import { message } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import { driverReturnOrderApi } from '@/api/business/storage/returnwarehouse-api'
import { useLoadingStore } from '@/store/modules/loading-store'
import { useEnums } from '@/hooks/plugins/useEnums'

const loadingStore = useLoadingStore()
const { getDescByValue } = useEnums()

defineExpose({
  showDrawer
})
const emit = defineEmits(['reload-list'])

// --------------------- Drawer 显示与隐藏 ---------------------
// 签收备注
const sign_remark = ref('')
// 是否展示
const visible = ref(false)
// 详情
const options = ref({})
const optionsList = ref({})

function showDrawer(item) {
  sign_remark.value = ''
  options.value = item
  singleDetail(item)
  visible.value = true
}

const onClose = () => {
  visible.value = false
}

const showLogModal = ref(false)
function changeLogModal(status: boolean) {
  showLogModal.value = status
}

// --------------------- 入库商品 ---------------------
// 将 tableData 从 computed 改为 ref
const tableData = ref<any[]>([])

// 表格列配置
const columns = reactive([
  { title: '商品名称', dataIndex: 'goods_name', width: 150, fixed: 'left' },
  { title: '大规格数量', dataIndex: 'large_editable_qty', width: 120 },
  { title: '大规格单位', dataIndex: 'large_unit_name', width: 80 },
  { title: '中规格数量', dataIndex: 'medium_editable_qty', width: 120 },
  { title: '中规格单位', dataIndex: 'medium_unit_name', width: 80 },
  { title: '小规格数量', dataIndex: 'small_editable_qty', width: 120 },
  { title: '小规格单位', dataIndex: 'small_unit_name', width: 80 },
  { title: '生产日期', dataIndex: 'batch_time', width: 150 },
  { title: '备注', dataIndex: 'goods_remark', width: 150 }
])

// --------------------- 弹窗 ---------------------
const caigouLoading = ref(false)

// 提交签收
const submit = async () => {
  // 验证生产日期
  const hasEmptyBatchTime = tableData.value.some((item: any) => !item.batch_time)
  if (hasEmptyBatchTime) {
    message.error('请填写所有商品的生产日期')
    return
  }

  // 构建batch数据
  const batchList: any[] = []

  tableData.value.forEach((item: any) => {
    // 为每个有规格ID和数量的规格生成batch记录
    if (item.large_spec_id && item.large_editable_qty > 0) {
      batchList.push({
        goods_id: item.goods_id,
        spec_id: item.large_spec_id,
        batch_time: item.batch_time,
        quantity: item.large_editable_qty
      })
    }
    if (item.medium_spec_id && item.medium_editable_qty > 0) {
      batchList.push({
        goods_id: item.goods_id,
        spec_id: item.medium_spec_id,
        batch_time: item.batch_time,
        quantity: item.medium_editable_qty
      })
    }
    if (item.small_spec_id && item.small_editable_qty > 0) {
      batchList.push({
        goods_id: item.goods_id,
        spec_id: item.small_spec_id,
        batch_time: item.batch_time,
        quantity: item.small_editable_qty
      })
    }
  })

  if (batchList.length === 0) {
    message.error('请至少填写一个签收数量')
    return
  }

  // 判断return_status: 如果有任何数量小于初始值，则为3(部分签收)，否则为2(完全签收)
  let return_status = 2 // 2 = 已完成
  for (const item of tableData.value) {
    if (item.large_editable_qty < item.large_initial_qty || item.medium_editable_qty < item.medium_initial_qty || item.small_editable_qty < item.small_initial_qty) {
      return_status = 3 // 3 = 部分签收
      break
    }
  }

  const params = {
    id: options.value.id,
    return_status: return_status,
    batch: JSON.stringify(batchList),
    sign_remark: sign_remark.value
  }

  caigouLoading.value = true
  try {
    const res = await driverReturnOrderApi.driverReturnOrderSign_in(params)
    message.success(res.msg)
    onClose()
    emit('reload-list')
  } catch (error: any) {
    message.error(error.msg || '签收失败')
    errorSentry.captureError(error)
  } finally {
    caigouLoading.value = false
  }
}

// --------------------- 详情 ---------------------
// 获取详情
// 在获取详情后，手动转换数据
async function singleDetail(rowData: any) {
  try {
    loadingStore.show()
    const res = await driverReturnOrderApi.driverReturnOrderOrder({ id: rowData.id, is_sign_detail: 1 })
    optionsList.value = res.data

    // 转换商品数据并赋值给 ref
    if (res.data?.goodsGroup) {
      tableData.value = res.data.goodsGroup.map((item: any) => {
        // 按unit_type映射规格信息
        const specMap = {
          1: { spec_id: null, unit_name: '-' }, // 小
          2: { spec_id: null, unit_name: '-' }, // 中
          3: { spec_id: null, unit_name: '-' } // 大
        }

        item.specs?.forEach((spec: any) => {
          if (specMap[spec.unit_type]) {
            specMap[spec.unit_type] = {
              spec_id: spec.id,
              unit_name: spec.unit_name || '-'
            }
          }
        })

        return {
          ...item,
          // 大规格
          large_spec_id: specMap[3].spec_id,
          large_unit_name: specMap[3].unit_name,
          large_initial_qty: item.return_qty_whole || 0,
          large_editable_qty: item.return_qty_whole || 0,

          // 中规格
          medium_spec_id: specMap[2].spec_id,
          medium_unit_name: specMap[2].unit_name,
          medium_initial_qty: item.return_qty_medium || 0,
          medium_editable_qty: item.return_qty_medium || 0,

          // 小规格
          small_spec_id: specMap[1].spec_id,
          small_unit_name: specMap[1].unit_name,
          small_initial_qty: item.return_qty_scattered || 0,
          small_editable_qty: item.return_qty_scattered || 0,

          // 生产日期
          batch_time: ''
        }
      })
    }
  } catch (e: any) {
    message.error(e.msg || '获取详情失败')
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}
</script>
